package com.hnepri.fang.ftx.fetch.residentialDetail;

import com.hnepri.fang.ftx.fetch.HttpUtil;
import com.hnepri.fang.ftx.model.ResidentialDetail;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 小区明细页解析
 */
public class ResidentialDetailPageParser {
    private static Pattern projectCodePattern = Pattern.compile("projcode:\"([^\"]+)\"");
    private static Pattern projectCodePattern2 = Pattern.compile("var\\s+newcode\\s+=\\s+\"(.+?)\";");
    private static Pattern corPattern = Pattern.compile("px:\"([^\"]+)\",py:\"([^\"]+)\"");
    //获得小区明细页链接
    public static String getDetailLink(String html) {
        Document doc = Jsoup.parseBodyFragment(html);
        Elements eles = doc.select("div.laybox ul a");
        for(int i = 0; i < eles.size(); i++) {
            Element node = eles.get(i);
            if (node.text().trim().equals("小区详情")) {
                return node.attr("href");
            }
        }
        return "";
    }


    //设置基本信息属性
    private static void setJbxxPro(Element ele, Map<String,String> prop) {
        Element dlNode = ele.select("div.inforwrap>dl").get(0);
        List<Element> childs = dlNode.children();
        for (Element ddDom: childs) {
            String title = ddDom.attr("title");
            if (title != null && !title.trim().equals("")) {
                //得到key后，去引号，去空格
                String key = ddDom.select("strong").text().trim();
                if (key.indexOf("本段") != -1)continue;
                key = key.replace("&nbsp;", "").replaceAll("\\s", "");
                key = key.substring(0, key.length() - 1);
                prop.put(key, title);
            } else {
                String key = ddDom.select("strong").text().trim();
                key = key.replace("&nbsp;", "").replaceAll("\\s", "");
                key = key.substring(0, key.length() - 1);
                if (key.indexOf("本段") != -1)continue;
                //如果值在span中
                if (ddDom.select("span").size() > 0) {
                    Element vSpan = ddDom.select("span").first();
                    String vTitle = vSpan.attr("title");
                    if (vTitle != null && !vTitle.trim().equals("")) {
                        prop.put(key, vTitle);
                    } else {
                        prop.put(key, vSpan.text());
                    }
                } else {
                    List<Node> childNodes = ddDom.childNodes();
                    String v = childNodes.get(1).toString().trim();
                    prop.put(key, v);
                }
            }
        }
    }
    //设置配套设施属性
    private static void setPtssPro(Element ele, Map<String,String> prop) {
        Element dlNode = ele.select("div.inforwrap>dl").get(0);
        List<Element> childs = dlNode.children();
        for (Element ddDom: childs) {
            String title = ddDom.attr("title");
            if (title != null && !title.trim().equals("")) {
                //得到key后，去引号，去空格
                String key = ddDom.select("strong").text().trim();
                key = key.replace("&nbsp;", "").replaceAll("\\s", "");
                key = key.substring(0, key.length() - 1);
                if (key.indexOf("本段") != -1)continue;
                prop.put(key, title);
            } else {
                String key = ddDom.select("strong").text().trim();
                key = key.replace("&nbsp;", "").replaceAll("\\s", "");
                key = key.substring(0, key.length() - 1);
                if (key.indexOf("本段") != -1)continue;
                //如果值在span中
                if (ddDom.select("span").size() > 0) {
                    Element vSpan = ddDom.select("span").first();
                    String vTitle = vSpan.attr("title");
                    if (vTitle != null && !vTitle.trim().equals("")) {
                        prop.put(key, vTitle);
                    } else {
                        prop.put(key, vSpan.text());
                    }
                } else {
                    List<Node> childNodes = ddDom.childNodes();
                    String v = childNodes.get(1).toString().trim();
                    prop.put(key, v);
                }
            }
        }
    }
    //设置交通状况属性
    private static void setJtzkPro(Element ele, Map<String,String> prop) {
        Elements ddDoms = ele.select("div.inforwrap dt");
        List<Node> childs = ddDoms.get(0).childNodes();
        StringBuilder sb = new StringBuilder();
        for (Node n:childs) {
            if (n.nodeName().equals("br")) {
                sb.append("|");
            } else {
                sb.append(n.toString().trim());
            }

        }
        prop.put("jtzk", sb.toString());
    }
    //设置周边信息属性
    private static void setZbxxPro(Element ele, Map<String,String> prop) {
        Elements ddDoms = ele.select("div.inforwrap dt");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ddDoms.size(); i++) {
            String id = ddDoms.get(i).attr("id");
            if (id != null && !id.trim().equals("")) continue;
            sb.append(ddDoms.get(i).text() + "|");
        }
        prop.put("zbxx", sb.toString());
    }
    //设置地理位置属性--暂时不再需要
    private static void setDlwzPro(Element ele, ResidentialDetail detail) throws IOException {
        String url = ele.select("iframe").attr("src");
        String html = HttpUtil.getResidentialDetailPageHtml(url);
        Document doc = Jsoup.parseBodyFragment(html);
        Elements scripts = doc.select("script");
        for (int i = 0; i < scripts.size(); i++) {
            List<Node> cnodes = scripts.get(i).childNodes();
            if (cnodes.size() > 0 ) {
                String scriptText = cnodes.get(0).toString();
                if (scriptText.indexOf("mapInfo") != -1) {
                    Matcher corM = corPattern.matcher(scriptText);
                    if (corM.find()) {
                        detail.setX(corM.group(1));
                        detail.setY(corM.group(2));
                    }
                    Matcher codeM = projectCodePattern.matcher(scriptText);
                    if (codeM.find()) {
                        detail.setProjcode(codeM.group(1));
                    }
                }
            }

        }
    }

    /**
     * 设置projcode
     * @param doc
     * @param detail
     */
    private static void setCode(Document doc, ResidentialDetail detail) {
        Elements scripts = doc.select("script");
        for (int i = 0; i < scripts.size(); i++) {
            List<Node> cnodes = scripts.get(i).childNodes();
            if (cnodes.size() > 0 ) {
                String scriptText = cnodes.get(0).toString();
                if (scriptText.indexOf("projname") != -1) {
                    Matcher codeM = projectCodePattern2.matcher(scriptText);
                    if (codeM.find()) {
                        detail.setProjcode(codeM.group(1));
                        break;
                    }
                }
            }

        }
    }
    public static ResidentialDetail parse(String html) throws IOException {
        ResidentialDetail detail = new ResidentialDetail();
        Document doc = Jsoup.parseBodyFragment(html);
        Elements eles = doc.select("body>div.wrap>div.con>div.con_left>div.box:gt(0)");
        Map<String,String> prop = new HashMap<>();
        for (int i = 0; i < eles.size(); i++) {
            Element ele = eles.get(i);
            String title = ele.select("div.box_tit h3").text().trim();
            if ("基本信息".equals(title)) {
                setJbxxPro(ele, prop);
            } else if ("配套设施".equals(title)) {
                setPtssPro(ele, prop);
            } else if ("交通状况".equals(title)) {
                setJtzkPro(ele, prop);
            } else if ("周边信息".equals(title)) {
                setZbxxPro(ele, prop);
            }
        }
        setCode(doc, detail);
        detail.setProp(prop);
        return detail;
    }
}
